package com.yumingjaing.service;

import com.google.common.cache.LoadingCache;
import com.yumingjaing.cache.guava.CacheConf;
import com.yumingjaing.cache.guava.CacheFactory;
import com.yumingjaing.cache.User;
import com.yumingjaing.cache.UserInfoCacheLoader;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutionException;

/**
 * @description:
 * @author: John
 * @version: UserService.java, v1.0 2024年12月14日 03:38
 */
@Slf4j
@Service("userService")
public class UserServiceImpl{

    /**
     * 注入缓存工厂对象
     */
    @Autowired
    private CacheFactory guavaCacheFactory;

    private LoadingCache<String, User> userCache;

    public User queryUserByName(String name){
        try {
            return userCache.get(name);
        } catch (ExecutionException e) {
            log.error(e.getMessage(),e);
            return null;
        }
    }

    /**
     * 在服务类创建完后对userCache做初始化
     */
    @PostConstruct
    public void init(){
        log.info("userCache start init...");
        CacheConf cacheConf = new CacheConf();
        cacheConf.setCacheName("USER_CACHE");
        cacheConf.setExpireTime(1);
        cacheConf.setMaximumSize(10000);

        userCache = guavaCacheFactory.buildCache(cacheConf,new UserInfoCacheLoader());

        log.info("userCache init completed.");
    }
}